package com.cw.mybatis.starter.handler;

import java.util.Date;

import org.apache.ibatis.reflection.MetaObject;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;

import lombok.extern.slf4j.Slf4j;

/**
 * MP注入处理器
 *
 * @author chenw
 * @date 2021/4/25
 */
@Slf4j
public class CreateAndUpdateMetaObjectHandler implements MetaObjectHandler {

	@Override
	public void insertFill(MetaObject metaObject) {
		try {
			//根据属性名字设置要填充的值
			if (metaObject.hasGetter("createTime")) {
				if (metaObject.getValue("createTime") == null) {
					this.setFieldValByName("createTime", new Date(), metaObject);
				}
			}
			if (metaObject.hasGetter("createBy")) {
			    this.setFieldValByName("createBy", "", metaObject);
			}
            if (metaObject.hasGetter("updateBy")) {
                this.setFieldValByName("updateBy", "", metaObject);
            }
            if (metaObject.hasGetter("updateTime")) {
                this.setFieldValByName("updateTime", new Date(), metaObject);
            }
		} catch (Exception e) {
			log.info("自动注入异常 => " + e.getMessage());
		}
	}

	@Override
	public void updateFill(MetaObject metaObject) {
		try {
			if (metaObject.hasGetter("updateBy")) {
			    this.setFieldValByName("updateBy", "", metaObject);
			}
			if (metaObject.hasGetter("updateTime")) {
			    this.setFieldValByName("updateTime", new Date(), metaObject);
			}
		} catch (Exception e) {
			log.info("自动注入异常 => " + e.getMessage());
		}
	}

}
